<template>
  <div>
    <el-dialog v-model="dialog.visible" :title="dialog.title" @close="hide()">
      <div class="content">
        <div class="flex items-start mt-[20px] left">
          <div class="w-[200px] border-solid border-1px border-[#dcdfe6] h-[533px] mr-[10px] overflow-y-scroll userlist">
            <div
              class="flex items-center justify-between px-[15px] py-[8px] cursor-pointer userItem"
              v-for="(item, index) in userList"
              :key="index"
              :class="curAdvertiserIndex === index ? 'bg-[#ECF5FF]' : ''"
              @click="selectUser(index)"
            >
              <div class="text-cut info">
                <div class="text-cut name">{{ item.name }}</div>
                <div class="text-cut mt-[3px] text-[12px] text-[#ccc] id">ID:{{ item.id }}</div>
              </div>
              <div class="shrink-0 action">
                <el-icon v-if="item.anchorId" color="#197AFB"><SuccessFilled /></el-icon>
                <el-icon v-else><CircleCheck /></el-icon>
              </div>
            </div>
          </div>
          <div class="flex flex-col productlist">
            <div class="flex items-center justify-between searchbox">
              <div class="flex items-center">
                <el-input v-model="keywords" placeholder="请输入关键词" clearable @clear="clearSearch" />
                <el-button class="ml-[15px]" @click="toSearch">查询</el-button>
              </div>
              <div class="btnbox">
                <el-button type="primary" class="ml-[15px]" :loading="loading" @click="getMircoAppList">同步</el-button>
              </div>
            </div>
            <div class="pt-[15px] flex">
              <div class="w-[500px] border-solid border-1px border-[#dcdfe6] contlist">
                <div class="h-[484px] cont">
                  <el-table
                    class="myTable"
                    height="440"
                    ref="tableRef"
                    :data="productList"
                    row-key="appId"
                    @selection-change="handleSelectionChange"
                    v-loading="loading"
                    @row-click="handelRowClick"
                  >
                    <el-table-column type="selection" width="55" />
                    <el-table-column property="anchorName" label="名称" />
                    <el-table-column property="anchorId" label="ID" />
                  </el-table>
                  <pagination
                    size="small"
                    v-show="total > 0"
                    :total="total"
                    layout=" prev, pager, next"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getMircoAppList"
                  />
                </div>
              </div>
              <div class="text-[14px] ml-[10px] h-[484px] w-[200px] selectlist">
                <div class="flex justify-between items-center border-solid border-1px px-[15px] py-[4px] border-[#dcdfe6] selectAcout">
                  <div class="numtxt">已选({{ selectRows[curAdvertiserIndex]?.length || 0 }}/1)</div>
                  <div
                    class="cursor-pointer action"
                    :class="selectRows[curAdvertiserIndex]?.length ? 'text-[#297bfb]' : 'text-[#a9c5f1]'"
                    @click="clearAll"
                  >
                    清空
                  </div>
                </div>
                <div class="h-[455px] border-solid border-1px border-[#dcdfe6] border-t-0 listbox">
                  <div
                    class="flex justify-between items-center px-[15px] py-[8px] bg-[#fafafa] cursor-pointer item"
                    v-for="(item, index) in selectResult[curAdvertiserIndex]"
                    :key="index"
                  >
                    <div class="text">
                      {{ item.anchorName }}
                    </div>
                    <div class="cursor-pointer action" @click="clearAll">
                      <el-icon><Close /></el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button plain @click="hide()">取消</el-button>
        <el-button type="primary" plain @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  byteMircroAppList,
  wechatMircroAppList,
  queryToolsMicroAppNew,
  getAllWechatApplet,
  type MicroAppQuery,
  type ByteMicroAppItem,
  type WechatMircroAppItem,
  type ByteMicroAppVO,
  type WechatMicroAppVO
} from '@/api/com';

import { listNativeAnchor } from '@/api/advertisement/nativeAnchor';
import { AnchorQuery, AnchorVO } from '@/api/advertisement/nativeAnchor/types';

import { useAppStore } from '@/store/modules/app';
import { debounce } from 'lodash';

type SelectAccountType = {
  id: number | string;
  name: string;
  anchorId: number | string;
  anchorType: number | string;
  anchorName: string;
  limit?: number;
  isCur?: boolean;
  instanceId?: string;
};

const props = defineProps<{
  advertiserId: any[];
  type: string;
}>();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const appStore = useAppStore();

const emit = defineEmits(['getAppInfo']);

const dialog = reactive<DialogOption>({
  visible: false,
  title: '锚点选择'
});

const userList = ref<any[]>([]);

const keywords = ref('');

const loading = ref(false);

// const productList = ref<WechatMicroAppVO | ByteMicroAppVO>();

const productList = ref<any[]>([]);

// const selectRows = ref<any[]>([]); //考虑后期多帐号对应不同商品
const selectRows = ref<Array<any[]>>(Array.from({ length: props.advertiserId.length }, () => []));

const selectResult = ref<Array<any[]>>(Array.from({ length: props.advertiserId.length }, () => []));

const tableRef = ref(null);

const curAdvertiserId = computed(() => {
  return userList.value[curAdvertiserIndex.value].id || 0;
});

const curAdvertiserIndex = ref(0);

const total = ref(0);

const initFormQuery: MicroAppQuery = {
  pageNum: 1,
  pageSize: 10,
  accountId: appStore.accountId, //账号id
  advertiserId: null, //广告主ID
  searchKey: null
};

const queryParams = ref<MicroAppQuery>({ accountId: appStore.accountId, advertiserId: curAdvertiserId, ...initFormQuery });

const updateRow = (item) => {
  selectRows.value[curAdvertiserIndex.value] = [item];
  tableRef.value?.toggleRowSelection(item, true);
  selectResult.value[curAdvertiserIndex.value] = [
    {
      id: curAdvertiserId.value,
      name: userList.value[curAdvertiserIndex.value].name,
      anchorId: item.anchorId,
      anchorType: item.anchorType,
      anchorName: item.anchorName
    }
  ];
  userList.value[curAdvertiserIndex.value].anchorType = item.anchorType;
  userList.value[curAdvertiserIndex.value].anchorId = item.anchorId;
  userList.value[curAdvertiserIndex.value].anchorName = item.anchorName;
};

const handelRowClick = (row) => {
  const checkRowIndex = selectRows.value[curAdvertiserIndex.value].findIndex((item) => item.instanceId === row.instanceId);
  if (checkRowIndex !== -1) {
    tableRef.value?.toggleRowSelection(row, false);
    selectRows.value.splice(checkRowIndex, 1);
    clearUserAppInfo();
  } else {
    updateRow(row);
  }
};

/**
 * tabel选择切换
 */
const handleSelectionChange = (selection: WechatMircroAppItem[] | ByteMicroAppItem[]) => {
  let newSelection = selection;
  if (newSelection.length == 0) {
    newSelection = selectRows.value[curAdvertiserIndex.value];
    // table里面的勾选回显
    newSelection.forEach((item) => {
      tableRef.value?.toggleRowSelection(item, true);
    });
  }
  if (newSelection.length || selectRows.value[curAdvertiserIndex.value].length) {
    if (selectRows.value.length > newSelection.length) {
      clearUserAppInfo();
    } else {
      newSelection.forEach((item, index) => {
        const isLastItem = index === newSelection.length - 1;
        if (isLastItem) {
          updateRow(item);
        } else {
          tableRef.value?.toggleRowSelection(item, false);
        }
      });
    }
  } else {
    if (selectRows.value[curAdvertiserIndex.value].length) {
      tableRef.value?.toggleRowSelection(selectRows.value[curAdvertiserIndex.value], true);
    } else {
      // 清空选择状态
      selectRows.value[curAdvertiserIndex.value] = [];
      selectResult.value[curAdvertiserIndex.value] = [];
      userList.value[curAdvertiserIndex.value].anchorType = null;
      userList.value[curAdvertiserIndex.value].anchorId = null;
      userList.value[curAdvertiserIndex.value].anchorName = null;
      tableRef.value?.clearSelection();
    }
  }
  
};
/**
 *  清除用户已选数据
 */
const clearUserAppInfo = () => {
  selectRows.value[curAdvertiserIndex.value] = [];
  selectResult.value[curAdvertiserIndex.value] = [];
  userList.value[curAdvertiserIndex.value].anchorType = null;
  userList.value[curAdvertiserIndex.value].anchorId = null;
  userList.value[curAdvertiserIndex.value].anchorName = null;
};
/**
 *  切换用户
 */
const selectUser = (i: number) => {
  if (curAdvertiserIndex.value === i) return;
  curAdvertiserIndex.value = i;
  getMircoAppList();
};

/**
 * 搜索
 */
const search = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  queryParams.value.searchKey = keywords.value;
  getMircoAppList();
};
/**
 *  条件搜索
 */
const searchQuery = () => {
  if (!keywords.value) {
    proxy?.$modal.msgError('请输入关键字');
    return;
  }
  search();
};
const toSearch = debounce(searchQuery, 300);
/**
 *  清空搜索
 */
const clearSearch = debounce(search, 300);

const submit = () => {
  let isComplete = true;
  userList.value.map((item) => {
    if (!isComplete) return;
    isComplete = !item.anchorId ? false : true;
  });
  if (!isComplete) {
    proxy?.$modal.msgError('请为帐户选择锚点');
    return;
  }
  emit('getAppInfo', userList.value);
  hide();
};

watch(
  () => props.advertiserId,
  () => {
    nextTick(() => {
      init();
    });
  },
  { immediate: true }
);

const init = () => {
  userList.value = JSON.parse(JSON.stringify(props.advertiserId));
  userList.value.map((item, index) => {
    if (curAdvertiserIndex.value === 0 && index === 0) {
      //请求小程序列表
      getMircoAppList();
    }
  });
};

const clearAll = () => {
  selectRows.value = Array.from({ length: props.advertiserId.length }, () => []);
  selectResult.value = Array.from({ length: props.advertiserId.length }, () => []);
  tableRef.value?.clearSelection();
  userList.value[curAdvertiserIndex.value].anchorId = null;
  userList.value[curAdvertiserIndex.value].anchorName = null;
};

const getMircoAppList = async () => {
  loading.value = true;
  queryParams.value.advertiserId = curAdvertiserId.value as number;

  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  const res = await listNativeAnchor(queryParams.value);
  productList.value = res.rows;

  // if (selectRows.value[curAdvertiserIndex.value].length) {
  //   setTimeout(() => {
  //     tableRef.value?.toggleRowSelection(selectRows.value[curAdvertiserIndex.value][0], true);
  //   }, 100);
  // }
  if (userList.value[curAdvertiserIndex.value].appId) {
    productList.value.map((item) => {
      if (item.anchorId === userList.value[curAdvertiserIndex.value].anchorId) {
        selectRows.value[curAdvertiserIndex.value] = item;
        setTimeout(() => {
          tableRef.value?.toggleRowSelection(item, true);
        }, 20);
      }
    });
  }

  loading.value = false;
};

onMounted(() => {
  nextTick(() => {
    init();
  });
});

const show = () => {
  if (!props.advertiserId) return;
  if (props.advertiserId.length) {
    init();
  }
  dialog.visible = true;
};
const hide = () => {
  curAdvertiserIndex.value = 0;
  dialog.visible = false;
};

defineExpose({ show, hide });
</script>

<style lang="scss" scoped>
::v-deep(.myTable) {
  thead {
    th:nth-child(1) {
      .cell {
        display: none;
      }
    }
  }
  .el-table__row {
    cursor: pointer !important;
  }
}
::v-deep(.pagination-container) {
  margin: 0 !important;
  height: auto;
}
::v-deep(.pagination-container .el-pagination) {
  float: unset;
}
::v-deep(.el-table--fit .el-table__inner-wrapper:before) {
  display: none;
}
</style>
